from flask import Flask, jsonify, request, send_from_directory
from flask_cors import CORS
import json
import random
from datetime import datetime, timedelta
import os

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 模拟数据库数据
def generate_mock_data():
    """生成模拟数据"""
    
    # 进度数据
    progress_data = [
        {
            "orderId": "WO-2024-001",
            "factory": "factory1",
            "workshop": "workshop1", 
            "line": "line1",
            "inputQty": 1000,
            "completedQty": 850,
            "yield": 98.5,
            "defectQty": 13,
            "orderCompletedQty": 850,
            "scrapQty": 5,
            "reworkQty": 8,
            "status": "running",
            "startTime": "2024-01-15 08:00:00",
            "estimatedEndTime": "2024-01-16 16:00:00"
        },
        {
            "orderId": "WO-2024-002",
            "factory": "factory1",
            "workshop": "workshop2",
            "line": "line2", 
            "inputQty": 800,
            "completedQty": 800,
            "yield": 99.2,
            "defectQty": 6,
            "orderCompletedQty": 800,
            "scrapQty": 2,
            "reworkQty": 4,
            "status": "completed",
            "startTime": "2024-01-14 08:00:00",
            "endTime": "2024-01-15 14:30:00"
        },
        {
            "orderId": "WO-2024-003",
            "factory": "factory2",
            "workshop": "workshop1",
            "line": "line1",
            "inputQty": 1200,
            "completedQty": 600,
            "yield": 97.8,
            "defectQty": 26,
            "orderCompletedQty": 600,
            "scrapQty": 8,
            "reworkQty": 18,
            "status": "running",
            "startTime": "2024-01-15 10:00:00",
            "estimatedEndTime": "2024-01-17 12:00:00"
        },
        {
            "orderId": "WO-2024-004",
            "factory": "factory2",
            "workshop": "workshop3",
            "line": "line3",
            "inputQty": 500,
            "completedQty": 0,
            "yield": 0,
            "defectQty": 0,
            "orderCompletedQty": 0,
            "scrapQty": 0,
            "reworkQty": 0,
            "status": "paused",
            "startTime": "2024-01-15 09:00:00",
            "pauseTime": "2024-01-15 11:30:00"
        },
        {
            "orderId": "WO-2024-005",
            "factory": "factory3",
            "workshop": "workshop1",
            "line": "line2",
            "inputQty": 900,
            "completedQty": 720,
            "yield": 98.9,
            "defectQty": 8,
            "orderCompletedQty": 720,
            "scrapQty": 3,
            "reworkQty": 5,
            "status": "running",
            "startTime": "2024-01-15 07:30:00",
            "estimatedEndTime": "2024-01-16 18:00:00"
        }
    ]
    
    # 品质数据
    quality_data = [
        {
            "orderId": "WO-2024-001",
            "strippingYield": 99.2,
            "interferenceYield": 98.8,
            "endInspectionYield": 99.5,
            "insertionLossYield": 98.9,
            "polarityYield": 99.1,
            "overallYield": 98.5,
            "lastUpdate": "2024-01-15 14:30:00"
        },
        {
            "orderId": "WO-2024-002",
            "strippingYield": 99.8,
            "interferenceYield": 99.5,
            "endInspectionYield": 99.9,
            "insertionLossYield": 99.2,
            "polarityYield": 99.6,
            "overallYield": 99.2,
            "lastUpdate": "2024-01-15 14:25:00"
        },
        {
            "orderId": "WO-2024-003",
            "strippingYield": 98.5,
            "interferenceYield": 97.9,
            "endInspectionYield": 98.2,
            "insertionLossYield": 97.5,
            "polarityYield": 98.1,
            "overallYield": 97.8,
            "lastUpdate": "2024-01-15 14:28:00"
        },
        {
            "orderId": "WO-2024-004",
            "strippingYield": 0,
            "interferenceYield": 0,
            "endInspectionYield": 0,
            "insertionLossYield": 0,
            "polarityYield": 0,
            "overallYield": 0,
            "lastUpdate": "2024-01-15 11:30:00"
        },
        {
            "orderId": "WO-2024-005",
            "strippingYield": 99.3,
            "interferenceYield": 99.1,
            "endInspectionYield": 99.4,
            "insertionLossYield": 98.8,
            "polarityYield": 99.2,
            "overallYield": 98.9,
            "lastUpdate": "2024-01-15 14:32:00"
        }
    ]
    
    # 人机料法环数据
    management_data = [
        {
            "process": "剥纤",
            "personnel": "张三",
            "equipment": "剥纤机-A01",
            "drawing": "已上传",
            "sop": "已上传",
            "temperature": "22°C",
            "humidity": "45%",
            "status": "正常",
            "lastMaintenance": "2024-01-10",
            "nextMaintenance": "2024-01-20"
        },
        {
            "process": "干涉",
            "personnel": "李四",
            "equipment": "干涉仪-B02",
            "drawing": "已上传",
            "sop": "已上传",
            "temperature": "23°C",
            "humidity": "46%",
            "status": "正常",
            "lastMaintenance": "2024-01-12",
            "nextMaintenance": "2024-01-22"
        },
        {
            "process": "端检",
            "personnel": "王五",
            "equipment": "端检仪-C03",
            "drawing": "已上传",
            "sop": "已上传",
            "temperature": "21°C",
            "humidity": "44%",
            "status": "正常",
            "lastMaintenance": "2024-01-11",
            "nextMaintenance": "2024-01-21"
        },
        {
            "process": "插回损",
            "personnel": "赵六",
            "equipment": "插回损测试仪-D04",
            "drawing": "已上传",
            "sop": "已上传",
            "temperature": "22°C",
            "humidity": "45%",
            "status": "正常",
            "lastMaintenance": "2024-01-09",
            "nextMaintenance": "2024-01-19"
        },
        {
            "process": "极性",
            "personnel": "钱七",
            "equipment": "极性测试仪-E05",
            "drawing": "已上传",
            "sop": "已上传",
            "temperature": "22°C",
            "humidity": "45%",
            "status": "正常",
            "lastMaintenance": "2024-01-08",
            "nextMaintenance": "2024-01-18"
        }
    ]
    
    return progress_data, quality_data, management_data

# 全局数据存储
progress_data, quality_data, management_data = generate_mock_data()

@app.route('/')
def index():
    """主页"""
    return send_from_directory('.', 'index.html')

@app.route('/api/progress')
def get_progress_data():
    """获取进度数据"""
    # 支持筛选参数
    factory = request.args.get('factory')
    workshop = request.args.get('workshop')
    line = request.args.get('line')
    status = request.args.get('status')
    
    filtered_data = progress_data
    
    if factory:
        filtered_data = [item for item in filtered_data if item['factory'] == factory]
    if workshop:
        filtered_data = [item for item in filtered_data if item['workshop'] == workshop]
    if line:
        filtered_data = [item for item in filtered_data if item['line'] == line]
    if status:
        filtered_data = [item for item in filtered_data if item['status'] == status]
    
    return jsonify({
        'success': True,
        'data': filtered_data,
        'total': len(filtered_data)
    })

@app.route('/api/quality')
def get_quality_data():
    """获取品质数据"""
    order_ids = request.args.getlist('orderIds')
    
    if order_ids:
        filtered_data = [item for item in quality_data if item['orderId'] in order_ids]
    else:
        filtered_data = quality_data
    
    return jsonify({
        'success': True,
        'data': filtered_data,
        'total': len(filtered_data)
    })

@app.route('/api/management')
def get_management_data():
    """获取人机料法环数据"""
    return jsonify({
        'success': True,
        'data': management_data,
        'total': len(management_data)
    })

@app.route('/api/dashboard')
def get_dashboard_data():
    """获取仪表板汇总数据"""
    total_orders = len(progress_data)
    running_orders = len([item for item in progress_data if item['status'] == 'running'])
    completed_orders = len([item for item in progress_data if item['status'] == 'completed'])
    paused_orders = len([item for item in progress_data if item['status'] == 'paused'])
    
    # 计算平均良率
    active_orders = [item for item in progress_data if item['status'] == 'running']
    avg_yield = sum(item['yield'] for item in active_orders) / len(active_orders) if active_orders else 0
    
    # 计算完成率
    total_input = sum(item['inputQty'] for item in progress_data)
    total_completed = sum(item['completedQty'] for item in progress_data)
    completion_rate = (total_completed / total_input * 100) if total_input > 0 else 0
    
    return jsonify({
        'success': True,
        'data': {
            'totalOrders': total_orders,
            'runningOrders': running_orders,
            'completedOrders': completed_orders,
            'pausedOrders': paused_orders,
            'avgYield': round(avg_yield, 1),
            'completionRate': round(completion_rate, 1),
            'lastUpdate': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
    })

@app.route('/api/refresh', methods=['GET', 'POST'])
def refresh_data():
    """刷新数据（模拟实时更新）"""
    global progress_data, quality_data, management_data
    
    # 模拟数据更新
    for item in progress_data:
        if item['status'] == 'running':
            # 随机增加完成数量
            if item['completedQty'] < item['inputQty']:
                increase = random.randint(1, 5)
                item['completedQty'] = min(item['completedQty'] + increase, item['inputQty'])
                
                # 更新良率
                if item['completedQty'] > 0:
                    item['yield'] = round(random.uniform(97.0, 99.5), 1)
                    item['defectQty'] = int(item['completedQty'] * (100 - item['yield']) / 100)
                
                # 检查是否完成
                if item['completedQty'] >= item['inputQty']:
                    item['status'] = 'completed'
                    item['endTime'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    # 更新品质数据
    for item in quality_data:
        if any(p['orderId'] == item['orderId'] and p['status'] == 'running' for p in progress_data):
            item['strippingYield'] = round(random.uniform(98.0, 99.9), 1)
            item['interferenceYield'] = round(random.uniform(97.5, 99.8), 1)
            item['endInspectionYield'] = round(random.uniform(98.5, 99.9), 1)
            item['insertionLossYield'] = round(random.uniform(97.0, 99.5), 1)
            item['polarityYield'] = round(random.uniform(98.0, 99.7), 1)
            item['overallYield'] = round((item['strippingYield'] + item['interferenceYield'] + 
                                        item['endInspectionYield'] + item['insertionLossYield'] + 
                                        item['polarityYield']) / 5, 1)
            item['lastUpdate'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    # 更新环境数据
    for item in management_data:
        item['temperature'] = f"{random.randint(20, 25)}°C"
        item['humidity'] = f"{random.randint(40, 50)}%"
    
    return jsonify({
        'success': True,
        'message': '数据已刷新',
        'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    })

@app.route('/api/filters')
def get_filters():
    """获取筛选选项"""
    factories = list(set(item['factory'] for item in progress_data))
    workshops = list(set(item['workshop'] for item in progress_data))
    lines = list(set(item['line'] for item in progress_data))
    statuses = list(set(item['status'] for item in progress_data))
    
    return jsonify({
        'success': True,
        'data': {
            'factories': factories,
            'workshops': workshops,
            'lines': lines,
            'statuses': statuses
        }
    })

@app.route('/api/order/<order_id>')
def get_order_detail(order_id):
    """获取工单详情"""
    progress = next((item for item in progress_data if item['orderId'] == order_id), None)
    quality = next((item for item in quality_data if item['orderId'] == order_id), None)
    
    if not progress:
        return jsonify({'success': False, 'message': '工单不存在'}), 404
    
    return jsonify({
        'success': True,
        'data': {
            'progress': progress,
            'quality': quality
        }
    })

@app.errorhandler(404)
def not_found(error):
    return jsonify({'success': False, 'message': '接口不存在'}), 404

@app.errorhandler(500)
def internal_error(error):
    return jsonify({'success': False, 'message': '服务器内部错误'}), 500

if __name__ == '__main__':
    print("光纤生产产线看板服务器启动中...")
    print("访问地址: http://localhost:19000")
    print("API文档:")
    print("  GET  /api/progress     - 获取进度数据")
    print("  GET  /api/quality      - 获取品质数据")
    print("  GET  /api/management   - 获取人机料法环数据")
    print("  GET  /api/dashboard    - 获取仪表板数据")
    print("  POST /api/refresh      - 刷新数据")
    print("  GET  /api/filters      - 获取筛选选项")
    print("  GET  /api/order/<id>   - 获取工单详情")
    
    app.run(host='0.0.0.0', port=19000, debug=True)
